package org.halk.myutils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * 对sql文件进行优化，单行插入，改为一次插入千行
 *
 * @author halk
 * @date 2025/10/29 17:37
 **/
public class OneInsertToMoreSql {

    public static void main(String[] args) {

        // 指定输入和输出目录
        String inputDir = "E:\\sql\\transformSql\\oneInsertSql";   // 输入SQL文件目录
        String outputDir = "E:\\sql\\transformSql\\result"; // 输出目录

        try {
            processSQLFiles(inputDir, outputDir);
            System.out.println("处理完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理目录下的所有SQL文件
     */
    public static void processSQLFiles(String inputDir, String outputDir) throws IOException {
        Files.createDirectories(Paths.get(outputDir));

        try (Stream<Path> paths = Files.walk(Paths.get(inputDir))) {
            paths.filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".sql"))
                    .forEach(path -> {
                        try {
                            processSingleFile(path, Paths.get(outputDir, path.getFileName().toString()));
                        } catch (IOException e) {
                            System.err.println("处理文件失败: " + path.toString());
                            e.printStackTrace();
                        }
                    });
        }
    }

    /**
     * 处理单个SQL文件
     */
    public static void processSingleFile(Path inputFile, Path outputFile) throws IOException {
        List<String> batchValues = new ArrayList<>();
        String insertPrefix = "";

        try (BufferedReader reader = Files.newBufferedReader(inputFile);
             BufferedWriter writer = Files.newBufferedWriter(outputFile, StandardOpenOption.CREATE)) {

            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || !line.startsWith("INSERT INTO")) {
                    continue;
                }

                // 提取INSERT前缀和VALUES部分
                Pattern pattern = Pattern.compile("(INSERT INTO `[^`]+` \\([^)]+\\) VALUES )(.+);");
                Matcher matcher = pattern.matcher(line);

                if (matcher.matches()) {
                    insertPrefix = matcher.group(1);
                    String valuesPart = matcher.group(2);
                    batchValues.add(valuesPart);

                    // 每1000行写入一次
                    if (batchValues.size() >= 1000) {
                        writeBatch(writer, insertPrefix, batchValues);
                        batchValues.clear();
                    }
                }
            }

            // 处理剩余不足1000行的数据
            if (!batchValues.isEmpty()) {
                writeBatch(writer, insertPrefix, batchValues);
            }
        }
    }

    /**
     * 写入一批INSERT语句
     */
    private static void writeBatch(BufferedWriter writer, String insertPrefix, List<String> batchValues)
            throws IOException {
        if (batchValues.isEmpty()) return;

        writer.write(insertPrefix);
        for (int i = 0; i < batchValues.size(); i++) {
            if (i > 0) {
                writer.write(",");
            }
            writer.write(batchValues.get(i));
        }
        writer.write(";\n");
    }

}
